/**
 * xtree
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/01/22
 * @version 1.0.0
 */
layui.define(["laytpl", "form"],function(exports){
    "use strict";
    var form = layui.form,
        hint = layui.hint(),
        $ = layui.$,
        xtree = {
            config:{
                domString:"",
                checkboxInputName:"ids",
                dataKeys:{
                    name:"name",
                    checked:"checked",
                    spread:"spread",
                    disabled:"disabled",
                    children:"children",
                    value:"id",
                    identification:"type"
                },
                identification:false,
                identiFun:function () {},
                icon:{
                    open:"&#xe625;",
                    close:"&#xe623;"
                },
                dataType:"json",
                ajaxType:"get",
                expand:false
            },
            cache:{}
        },
        thisXTree = function(){
            var that = this,
                options = that.config;
            return {
                getCheckedAll:function(){
                    return that.getCheckedAll.call(that);
                },
                config: options
            }
        },
        xTreeItemFilter = "xTreeItem",
        MOD_NAME = "xtree",
        ELEM_ITEM = 'layui-xtree-item';

    function Xtree(options){
        var that = this;
        that.config = $.extend({},that.config,xtree.config,options);
        that.render();
    }

    Xtree.prototype.render = function(){
        var that = this
            ,options = that.config
            ,othis = $(options.elem)
        if(!options.elem || $(options.elem).length ==0 ){
            hint.error("this elem not initial");
            return;
        }

        if(typeof options.data === "object"){
            that.dataBind(options.data);
            that.renderAfter();
        }else if(typeof options.data == "string"){
            $.ajax({
                type:options.ajaxType || "get",
                url:options.data,
                dataType:options.dataType,
                success:function(res){
                    that.dataBind(res);
                    that.renderAfter();
                },error: function(){
                    othis.html('<div class="layui-none">数据接口请求异常</div>');
                }
            });
        }
    };

    Xtree.prototype.renderAfter = function () {
        var that = this
            ,options = that.config
            ,othis = $(options.elem)
            ,hasRender = othis.next("." + ELEM_ITEM);
        //生成替代元素
        hasRender[0] && hasRender.remove(); //如果已经渲染，则Rerender
        othis.append(that.config.domString);
        form.render("checkbox");
        that.locationBind();
        that.expandEvent();
        that.formCheckBoxEvent();
    };

    Xtree.prototype.dataBind = function(data){
        var that = this;
        if(data.length > 0){
            for(var item in data) {
                that.config.domString += '<div class="' + ELEM_ITEM + '" style="margin: 5px 0px 0px 10px;">';
                if (data[item][that.config.dataKeys.children] && data[item][that.config.dataKeys.children].length > 0) {
                    that.config.domString += '<i class="layui-icon layui-xtree-icon '+ (that.config.expand ? "layui-xtree-expand" : "") +'" style="position: relative; top: 3px; margin: 0px 5px 0px 0px; font-size: 18px; color: rgb(47, 64, 86); cursor: pointer;">'+(that.config.expand ? that.config.icon.open : that.config.icon.close)+'</i>';
                } else {
                    that.config.domString += '<i class="layui-icon" style="position: relative; top: 3px; margin: 0px 5px 0px 0px; font-size: 18px; color: rgb(47, 64, 86);"></i>';
                }
                that.config.domString += '<input type="checkbox" name="'+that.config.checkboxInputName+'" lay-skin="primary" lay-filter="'+ xTreeItemFilter +'" value="' + data[item][that.config.dataKeys.value] + '" title="' + data[item][that.config.dataKeys.name] + '"';
                if (data[item][that.config.dataKeys.checked]) {
                    that.config.domString += 'checked=""';
                }
                that.config.domString += ' />';
                if(that.config.identification){
                    that.config.domString += that.config.identiFun(data[item][that.config.dataKeys.identification]);
                }
                if (data[item][that.config.dataKeys.children] && data[item][that.config.dataKeys.children].length > 0) {
                    that.dataBind(data[item][that.config.dataKeys.children]);
                }
                that.config.domString += '</div>';
            }
        }
    };

    Xtree.prototype.expandEvent = function () {
        var that = this
            ,options = that.config,
            othis = $(options.elem),
            item = othis.find("."+ELEM_ITEM).find(".layui-xtree-icon"),expandClass = "layui-xtree-expand";
        item.click(function(e){
            e.preventDefault();
            if($(this).hasClass(expandClass)){
                $(this).parent().children("."+ELEM_ITEM).css("display","none");
                $(this).html(options.icon.close);
                $(this).removeClass(expandClass);
            }else{
                $(this).parent().children("."+ELEM_ITEM).css("display","block");
                $(this).html(options.icon.open);
                $(this).addClass(expandClass);
            }
        });
    };

    Xtree.prototype.formCheckBoxEvent = function () {
        var that = this
            ,options = that.config,
            othis = $(options.elem),
            item = othis.find("."+ELEM_ITEM);
        form.on("checkbox("+xTreeItemFilter+")",function (item) {
            var childrens = $(this).parent().find("."+ELEM_ITEM),
                formCheckboxInput = "input[type='checkbox']";
            $.each(childrens,function(){
                $(this).find(formCheckboxInput)[0].checked = item.elem.checked;
            });
            form.render("checkbox");
            that.setParentCheck(item.elem);
        });
    };

    Xtree.prototype.setParentCheck = function(elem){
        var that = this;
        var node = $(elem).parent().parent();
        if(node.hasClass(ELEM_ITEM)){
            var nodeXTrees = node.children("."+ELEM_ITEM);
            var nodeCheckedCount = 0;
            for(var i=0;i<nodeXTrees.length;i++){
                if($(nodeXTrees[i]).find("input[type='checkbox']")[0].checked){
                    nodeCheckedCount++;
                }
            }
            if(nodeCheckedCount <= 0){
                node.find("input[type='checkbox']")[0].checked = false;
            }else{
                node.find("input[type='checkbox']")[0].checked = true;
            }
            form.render("checkbox");
            this.setParentCheck(node.find("input[type='checkbox']")[0]);
        }
    };

    Xtree.prototype.locationBind = function () {
        var that = this
            ,options = that.config;
        var othis = $(options.elem),
            xTreeItem = othis.find("." + ELEM_ITEM);
        for(var i = 0;i < xTreeItem.length; i++){
            var item = $(xTreeItem[i]);
            if(item.parent().hasClass(ELEM_ITEM)){
                item.css("margin","5px 0 0 25px");
                if(!options.expand){
                    item.css("display","none");
                }
            }else{
                item.css("margin","5px 0 0 10px");
            }
        }
    };

    Xtree.prototype.getCheckedAll = function () {
        var that = this,
            options = that.config,
            value = [];
        var checkboxes = $(options.elem).find("input[type='checkbox']");
        $.each(checkboxes,function(){
           if($(this)[0].checked){
               value.push($(this).val());
           }
        });
        return value;
    };

    xtree.render = function(options){
        var inst = new Xtree(options);
        return thisXTree.call(inst);
    };

    exports(MOD_NAME,xtree);
});
